from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
import requests
import base64
import urllib
import time
import cv2

chrome_options = Options()
# chrome_options.add_argument("--headless")
chrome_options.add_argument('window-size=1920x1080')  # 虚拟屏幕大小
browser = webdriver.Chrome(options=chrome_options)



def get_code(imgname):
    params = {"grant_type": "client_credentials", "client_id": "bt9brCIZy4MYnHzBUqpHOYbf",
              "client_secret": "SimOcnn7D9BDnvsh0euXmMuncCrZeXXZ"}
    res = requests.get("https://aip.baidubce.com/oauth/2.0/token", params=params)
    token = res.json()['access_token']
    # 定义头部信息
    headers = {'Content-Type': 'application/x-www-from/urlencoded'}
    url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + token
    # 读取图片
    with open(imgname, 'rb')as f:
        tem_img = base64.b64encode(f.read())
    # 进行base64编码
    temp_data = {'image': tem_img}
    # 请求视图接口
    res = requests.post(url=url, data=temp_data, headers=headers)
    mycode = ''
    word_dict = res.json()['words_result']
    for key in word_dict:
        mycode += key['words']
    return mycode


def get_url():
    url = 'http://127.0.0.1:8080/login'
    # 请求url
    browser.get(url)
    # 获取input标签 并输入
    browser.find_element_by_xpath('//table/tr[1]/td[1]/input').send_keys('test3')
    time.sleep(2)
    browser.find_element_by_xpath('//table/tr[2]/td[1]/input').send_keys('a123456')
    time.sleep(2)
    # 获取验证码标签 并截图到本地
    browser.find_element_by_xpath('//img[@class="code"]').screenshot('1.png')
    # 读图 去色：cv2.IMREAD_GRAYSCALE
    img = cv2.imread('1.png', cv2.IMREAD_GRAYSCALE)
    # 写图
    cv2.imwrite('2.png', img)
    # 调用打码函数 将图片名传进去 并填入验证码
    code = get_code('2.png')
    print(code)
    browser.find_element_by_xpath('//table/tr[4]/td[1]/input').send_keys(code)
    # 获取滑动模块标签
    button=browser.find_element_by_xpath('//div[@class="dv_handler dv_handler_bg"]')
    # 声明动作实例
    action = ActionChains(browser)
    # 点击并且按住
    action.click_and_hold(button).perform()
    action.reset_actions()
    # 实际拖动像素和轨迹长度是有出入的
    action.move_by_offset(271, 0).perform()
    # 点击登录
    time.sleep(2)
    browser.find_element_by_xpath('//button[@class="h-btn h-btn-blue"]').click()

def main():
    get_url()


if __name__ == '__main__':
    main()
    time.sleep(5)
    browser.close()
